package org.vectrics.client.webclient;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.VectricsException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.io.InputStream;
import java.io.IOException;


public class HttpRequester extends Requester {
	private transient Logger log = Logger.getLogger(HttpRequester.class);

	public HttpRequester() {
		super();
	}
	


	public ResponseResult execute(ServiceConnection connection, ServerCommand command) {
		ResponseResult result = null;
		try {
			Properties params = new Properties();
			command.getParameters(connection, params);
			String urlStr = "http://" + connection.getConfig().getIpAddress();
			if (connection.getConfig().getLocation() != null) {
				urlStr += connection.getConfig().getLocation();
			}
			
			if (connection.getSessionId() != null)
				urlStr += ";jsessionid=" + connection.getSessionId();
			
			String action = command.getCommandCode();
			boolean test = false;
		
		
		
			if (action != null) {
				HttpClient client = new HttpClient();
				client.setConnectionTimeout(10000);

				if (log.isDebugEnabled()) {
					log.debug("run() - sending request: " + urlStr);
				}
		
				//URL url = new URL(urlStr);
				if (log.isDebugEnabled()) {
					log.debug("execute() - request => " + urlStr);
				}
				
				PostMethod httpPost = new PostMethod(urlStr);
				Enumeration paramEnum = params.propertyNames();
				while (paramEnum.hasMoreElements()) {
					String paramName = (String)paramEnum.nextElement();
					String paramValue = params.getProperty(paramName);
					httpPost.addParameter(paramName, paramValue);
				}
				httpPost.addParameter("command", command.getCommandCode());
				int responseCode = client.executeMethod(httpPost);
				
				
		
				//httpURLConnection.connect();
				log.debug("run() - getting input stream from http connection");
				//int responseCode = httpURLConnection.getResponseCode();
				
				if (responseCode == 500) {
					log.debug("Informing command that we experienced an error");
					command.setError("Server could not find the service for issued command, make sures server is running an application to respond to your request.");
					
					log.debug("Even though the server could not find our page, we at least connected");
					connection.setConnectionStatus(ConnectionStatus.CONNECTED);
				}
				else if (responseCode == 400) {
					log.debug("Informing command that we experienced an error");
					command.connectionError("Server could not be found.");
					
					connection.setConnectionStatus(ConnectionStatus.DISCONNECTED);
				}
				else {
					InputStream is = httpPost.getResponseBodyAsStream();
			
					log.debug("run() - processing response");
					try {
						result = command.processResponse(connection, is);
					}
					catch (VectricsException ve) {
						log.error("Vectrics exception processing response with command", ve);
						throw new SystemException("Vectrics exception processing response with command", ve);
					}
					connection.setConnectionStatus(ConnectionStatus.CONNECTED);
				}
				httpPost.releaseConnection();
			}
		}
		catch (IOException ex) {
			String errorMsg = "IOException while communicating with server.  Address= " + connection.getConfig().getIpAddress() + " Message = " +  ex.getMessage();
			log.info(errorMsg, ex);
			connection.setConnectionStatus(ConnectionStatus.DISCONNECTED);
			command.connectionError(errorMsg);
			result = ResponseResult.SERVER_NOT_FOUND;
		}
		return(result);
	}

}
